<template>
  <el-card class="box-card" :body-style="{ height: '90%' }">
    <template #header>
      <div class="card-header">
        <span>人员情况</span>
        <el-button type="success" class='goTo' @click="goToTable">人员排期表</el-button>
      </div>
    </template>
    <div style="margin-bottom:15px">
      <span
        :style="{ width: '25px', height: '15px', background: colors.level1, display: 'inline-block', borderRadius: '4px', marginRight: '5px' }"></span><span
        style="color:rgb(70, 70, 70)">紧急项目</span>
      <span
        :style="{ width: '25px', height: '15px', background: colors.level2, display: 'inline-block', borderRadius: '4px', margin: '0 5px' }"></span><span
        style="color:rgb(70, 70, 70)">正常项目</span>
      <span
        :style="{ width: '25px', height: '15px', background: colors.level3, display: 'inline-block', borderRadius: '4px', margin: '0 5px' }"></span><span
        style="color:rgb(70, 70, 70)">长期项目</span>
    </div>
    <div class="kanban-single-lane-body">
      <div class="kanban-single-lane-body-wrapper" v-loading="loading" element-loading-text="加载中..."
        :element-loading-spinner="svg" element-loading-svg-view-box="-10, -10, 50, 50"
        element-loading-background="rgba(255, 255, 255, 0.8)">
        <div class="kanban-single-list" v-for="(o, index) in  personData " :key="o">
          <div class="kanban-single-list-contents">
            <div class="kanban-head">
              {{ o.member }}
            </div>
          </div>
          <div class="kanban-bucket">
            <div class="kanban-droppable-bucket kanban-droppable-bucket-single-list">
              <div class="kanban-dnd-card" @click="toEdit(a.id)" v-for="a in  o.projects " :key="a"
                v-if="o.projects.length > 0" :class="{
                  'completed': a.progress === 100,
                  'level-1': a.progress !== 100 && a.level === '1', 'level-2' : a.progress !==100 && a.level==='2' , 'level-3' :
                a.progress !==100 && a.level==='3' }">
                <div class="task-main">{{ a.product_name }}</div>
                <div class="task-other">{{ a.department_name }}</div>
                <div :class=" getBackgroundColor(a.deadline_date) " class="date" v-if=" a.progress === 0 ">
                  <span v-if=" a.work_date && a.deadline_date ">
                    {{ formatDate(a.work_date) }} - {{ formatDate(a.deadline_date) }}
                  </span>
                  <span v-else-if=" a.work_date ">
                    {{ formatDate(a.work_date) }} 开始
                  </span>
                  <span v-else-if=" a.deadline_date ">
                    {{ formatDate(a.deadline_date) }} 截止
                  </span>
                  <span v-else>
                    无日期
                  </span>
                </div>
                <div class="completeTag" v-if=" a.progress == 100 ">已完成</div>
                <div class="task-other">{{ a.notes }}</div>
                <el-popover v-if=" getOtherMembers(a.id, o.member) != '' " placement="top-start" title="其他成员" :width=" 200 "
                  trigger="hover">
                  <div v-html=" getOtherMembers(a.id, o.member) "></div>
                  <template #reference>
                    <div class="more">
                      <el-icon>
                        <User />
                      </el-icon>
                    </div>
                  </template>
                </el-popover>
              </div>
              <el-button type="primary" :icon=" Plus " @click="toAdd()"
                style="width:237px;background-color: rgb(171, 170, 172);border:none"><el-icon>
                  <Plus />
                </el-icon></el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import workApi from '../../api/work'
import userApi from '../../api/user'
import { useRouter } from 'vue-router'
const router = useRouter()
const personData = ref([])
const originalData = ref([])

const loading = ref(false);
const colors = {
  level1: '#fbe4d2',
  level2: '#e4f2d9',
  level3: '#fff3c9'
}

onMounted(async () => {
  getPersonList()
})

// 获取数据列表
const getPersonList = async () => {
  loading.value = true;
  try {
    const res = await workApi.getPersonList()
    originalData.value = res.data

    const currentDate = new Date();

    //把res.data中的member做处理
    let membersData = {}

    res.data.forEach((item) => {
      // 将成员字符串拆分为数组
      const members = item.member.split(',').map((member) => member.trim())

      // 遍历成员数组，创建新的对象
      members.forEach((member) => {
        if (!membersData[member]) {
          membersData[member] = []
        }

        //找到过期但未点完成的数据，直接改成完成
        if (item.deadline_date && new Date(item.deadline_date) < currentDate && item.progress < 100) {
          item.progress = 100; // 超过截止日期的项目标记为已完成
          const res1 = workApi.goComplete(item)
        }

        // 将项目信息加入成员对应的数组
        membersData[member].push({
          id: item.id,
          product_name: item.product_name,
          department_name: item.department_name,
          work_date: item.work_date,
          deadline_date: item.deadline_date,
          progress: parseInt(item.progress),
          other_member: item.member,
          notes: item.notes,
          level: item.level
        })
      })
    })

    // 对每个成员的项目进行排序，确保 progress = 100 的项目在最后
    Object.keys(membersData).forEach((key) => {
      membersData[key].sort((a, b) => a.progress - b.progress);
    });

    // 按照member首字母排序
    const sortedMembersData = {};
    Object.keys(membersData)
      .sort((a, b) => a.localeCompare(b))
      .forEach((key) => {
        sortedMembersData[key] = membersData[key];
      });

    membersData = sortedMembersData;

    const res1 = await userApi.getUserList() //获取所有用户列表
    const allPerson = res1.data

    // 遍历所有人员数组，为不在 membersData 中的人员生成空数组
    allPerson.forEach((person) => {
      const name = person.name

      if (!membersData[name] && parseInt(person.role) < 9) {
        membersData[name] = []
      }
    })

    personData.value = Object.keys(membersData).map((member) => ({
      member,
      projects: membersData[member],
      type: membersData[member].type,
    }))

    console.log(personData.value)
  } catch (error) {
    console.error('数据加载错误:', error);
    ElMessage.error('数据加载失败，请重试');
  } finally {
    loading.value = false;
  }
}

const getOtherMembers = (id, name) => {
  const memberList = originalData.value.find(item => item.id === id).member.split(",");
  const otherMembers = memberList.filter(member => member !== name);
  return otherMembers;
}


const toEdit = async (id) => {
  router.push({
    path: '/week_report/add',
    query: { id: id },
  })
}

const toAdd = async () => {
  router.push({
    path: '/week_report/add',
  })
}

const goToTable = async () => {
  router.push({
    path: '/member_report/table',
  })
}

const formatDate = (dateString) => {
  const dateObj = new Date(dateString);
  if (!isNaN(dateObj)) {
    return dateObj.toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' });
  }
  return '';
}

const getBackgroundColor = (deadline_date) => {
  if (!deadline_date) return 'bg-blue';
  const deadline = new Date(deadline_date);
  const currentDate = new Date();

  // Clear the time part of the dates
  deadline.setHours(0, 0, 0, 0);
  currentDate.setHours(0, 0, 0, 0);

  return deadline.getTime() < currentDate.getTime() ? 'bg-red' : 'bg-blue';
}


</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.kanban-single-lane-body {
  background-color: #f7f7f7;
  height: 90%;
  min-width: 100%;
  padding: 2px 0;
  overflow: auto;
}

.kanban-single-lane-body-wrapper {
  align-items: flex-start;
  border-radius: 4px;
  display: flex;
  height: 100%;
  overflow-y: hidden;
  width: 100%;
}

.kanban-single-list {
  flex-shrink: 0;
  height: 100%;
  padding: 4px 0;
}

.kanban-single-list-contents {
  background-color: #f7f7f7;
  border-radius: 4px;
}

.kanban-head {
  padding: 10px 25px;
  font-weight: bold;
}

.kanban-bucket {
  width: 246px;
  height: calc(100% - 48px);
  min-height: 96px;
  padding: 0 17px;
}

.kanban-progress {
  background: #86a5ff;
  position: absolute;
  height: 2%;
  bottom: 0;
  left: 0;
  border-radius: 10px 0 0 10px;
}

.kanban-progress-text {
  font-size: 12px;
  position: absolute;
  top: -8px;
  right: -30px;
  color: rgb(190 190 191);
}

.kanban-droppable-bucket {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
  margin-right: -10px;
}

.kanban-dnd-card {
  margin-bottom: 10px;
  outline: none;
  width: 218px;
  background-color: #fff;
  padding: 20px 10px 20px 10px;
  text-align: left;
  border-radius: 5px;
  position: relative;
  cursor: pointer;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.3);
}

.task-main {
  /* box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1); */
  position: relative;
  white-space: normal;
  width: 100%;
}

.task-other {
  /* box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1); */
  position: relative;
  white-space: normal;
  font-size: 14px;
  margin-top: 10px;
  color: #8c8c8c;
}

.box-card {
  width: 99%;
  height: 99%;
}

.more {
  width: 20px;
  height: 20px;
  background: #fff;
  position: absolute;
  bottom: 10px;
  right: 10px;
  text-align: center;
  cursor: pointer;
}

.more .el-icon {
  color: gray;
}

.bg-blue span {
  background-color: #1B9AEE;
  padding: 3px;
}

.bg-red span {
  background-color: #E62412;
  padding: 3px;
}

.date {
  color: #fff;
  font-size: 12px;
  margin-top: 10px;
}

.completed {
  opacity: 0.5;
}

.kanban-dnd-card.level-1 {
  background-color: #fbe4d2;
}

.kanban-dnd-card.level-2 {
  background-color: #e4f2d9;
}

.kanban-dnd-card.level-3 {
  background-color: #fff3c9;
}

.completeTag {
  display: inline-block;
  color: #1e9441;
  font-size: 12px;
  margin-top: 10px;
  background: rgba(42, 168, 78, .08);
}

.goTo {
  float: right;
  margin-right: 10px
}
</style>
